<template>
  <div
    ref="tGoods"
    :class="props.cardLayout === 'vertical' ? 'vertical-wrap' : ''"
  >
    <div class="goods-list">
      <div
        v-for="good in goodsList"
        :key="good.id"
        class="goods"
      >
        <el-card
          :body-style="{ padding: ' 5px' }"
          style="border-radius: 10px; padding: 10px"
        >
          <div class="good-item-wrap">
            <div
              v-if="showGoodsPhoto"
              class="carousel-wrap"
            >
              <el-carousel
                class="goods-carousel"
                direction="vertical"
                height="250px"
              >
                <el-carousel-item
                  v-for="goodsImg in good.imgList"
                  :key="goodsImg.url"
                >
                  <el-image
                    :preview-src-list="[...good.imgList.map(item => item.url)]"
                    :src="goodsImg.url"
                    class="goods-img"
                    preview-teleported
                  >
                    <template #error>
                      <div class="goods-image-slot">
                        <el-icon>
                          <ele-Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                </el-carousel-item>
              </el-carousel>
            </div>
            <div class="goods-info">
              <div class="goods-name">
                {{ good.goodsName }}
              </div>
              <div class="goods-desc">
                {{ good.description }}
              </div>
              <div
                :style="{ visibility: showInventory ? 'hidden' : 'visible' }"
                class="goods-desc mt100"
              >
                {{ $t("formgen.goodsConfig.inventory") }}:
                <span class="inventory">{{ good.remainInventory !== undefined ? good.remainInventory : good.inventory }}</span>
              </div>
              <div class="goods-count-wrap">
                <div class="price">
                  <span class="currency">￥</span>
                  <span class="value">
                    {{ getPrice(good) }}
                  </span>
                </div>
                <div class="count-input-wrap">
                  <el-input-number
                    v-model="good.count"
                    :max="good.purchaseLimit > 0 ? good.purchaseLimit : good.remainInventory ? good.remainInventory : 1000"
                    :min="0"
                    class="goods-count"
                    size="small"
                    @input="handleChangeGoodsNum(good)"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <div
      v-if="showTotalPrice"
      class="total-price-wrap"
    >
      <span class="total-text">{{ $t("formgen.goodsConfig.totalPrice") }}:</span>
      <span class="total-num">
        ¥
        <span class="num">
          {{ totalPrice }}
        </span>
      </span>
    </div>
  </div>
</template>

<script lang="ts" name="TGoods" setup>
import { computed, onMounted, PropType, useAttrs, watch } from "vue";
import { formEmits, formItemProps, useFormItem } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { getRequest } from "@/api/baseRequest";
import { useRoute } from "vue-router";
import { Good } from "./types";

const props = defineProps({
  ...formItemProps,
  goodsList: {
    type: Array as PropType<Good[]>,
    default: () => {
      return [];
    }
  },
  showInventory: {
    type: Boolean,
    default: true
  },
  showGoodsPhoto: {
    type: Boolean,
    default: false
  },
  showTotalPrice: {
    type: Boolean,
    default: false
  },
  cardLayout: {
    type: String,
    default: "vertical"
  }
});

const emits = defineEmits(formEmits);

const formItemHook = useFormItem(props, emits);

const { changeValue } = formItemHook;

onMounted(() => {
  // 非设计情况下查看库存
  if ("design" !== attrs.mode) {
    queryGoodsSellQuantity();
  }
  // 初始化库存
  initGoodsNum(props.value);
});

// 修复在逻辑下 显示时库存不显示出来
watch(
  () => props.value,
  (newVal: any) => {
    console.log(newVal);
    // 逻辑隐藏时会更新成{} 这里不在初始化选中数量 不然又会默认选中数量1
    if (newVal && Object.keys(newVal).length) {
      initGoodsNum(newVal);
    }
  },
  {
    deep: true
  }
);

const initGoodsNum = (newVal: any) => {
  if (props.goodsList && "design" !== props.mode) {
    // 填充默认值
    props.goodsList.forEach((good: any) => {
      good.count = undefined !== newVal[good.id] ? newVal[good.id] : 1;
      // 确保初始数量不超过限购数
      if (good.purchaseLimit && good.purchaseLimit > 0 && good.count > good.purchaseLimit) {
        good.count = good.purchaseLimit;
      } else if (good.purchaseLimit === undefined) {
        good.purchaseLimit = -1;
      }
    });
    props.goodsList.forEach((good: any) => {
      changeValue.value[good.id] = good.count;
    });
  }
};

const route = useRoute();
const attrs = useAttrs();

const queryGoodsSellQuantity = () => {
  getRequest("/form/ext/queryGoodsSellQuantity", {
    formKey: route.params.key,
    formItemId: attrs.vModel
  }).then(res => {
    let data = res.data;
    props.goodsList.forEach((goods: any, index) => {
      let remainInventory = goods?.inventory;
      if (data[goods?.id]) {
        remainInventory = goods.inventory - data[goods.id];
      }
      goods.remainInventory = remainInventory;
      props.goodsList[index] = goods;
    });
  });
};

const getPrice = (goods: any) => {
  return (goods.count * goods.price).toFixed(2);
};

const handleChangeGoodsNum = (goods: any) => {
  goods["finalPrice"] = goods.count * goods.price;
  changeValue.value[goods.id] = goods.count;
};

const totalPrice = computed(() => {
  if (!changeValue.value) {
    return 0;
  }
  let total = 0;
  Object.keys(changeValue.value).forEach(key => {
    const quantity = changeValue.value[key];
    const price = props.goodsList.find(good => good.id == Number(key))?.price || 0;
    // 将每次计算的结果都转换为整数计算，最后再转回小数
    total += Math.round(quantity * price * 100);
  });
  // 最后除以 100 并保留两位小数
  return (total / 100).toFixed(2);
});
</script>

<style lang="scss">
.goods-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 12px;

  .goods {
    width: calc(33.33% - 16px);
    min-width: 280px;

    .el-card__body {
      padding: 0;
    }
  }

  .goods-img {
    width: 100%;
    height: auto;
    object-fit: cover;
    border-radius: 5px;
  }

  .goods-image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 30px;
  }

  .goods-name {
    font-size: 16px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    margin: 0;
  }

  .goods-desc {
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    color: var(--el-text-color-secondary);
    display: -webkit-box;
    font-size: 14px;
    font-weight: 400;
    line-height: 18px;
    margin: 0;
    overflow: hidden;
    position: relative;
    white-space: pre-wrap;
  }

  .inventory {
    color: #000000;
  }

  .price {
    color: #e34152;
    font-weight: bold;
  }

  .goods-count-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 12px;
    padding: 8px 0;
  }
}

.edit-form-item .goods {
  width: 35%;
}

.vertical-wrap {
  @media screen and (min-width: 501px) {
    .goods {
      width: 100% !important;
      margin-bottom: 16px;
    }

    .good-item-wrap {
      display: flex;
      gap: 16px;
    }

    .carousel-wrap {
      width: 200px;
      min-width: 200px;
      height: 200px;
    }

    .goods-carousel {
      width: 200px !important;
      height: 200px !important;
    }

    .goods-img {
      width: 200px;
      height: 200px;
      object-fit: cover;
    }

    .goods-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 8px 0;
    }

    .goods-count-wrap {
      margin-top: 0;
    }
  }
}

// 移动端样式优化
@media screen and (max-width: 500px) {
  .goods-list {
    padding: 8px;

    .goods {
      width: 100% !important;
      margin-bottom: 12px;
    }

    .goods-img {
      height: auto;
    }

    .goods-info {
      padding: 12px 8px;
    }

    .goods-count-wrap {
      padding: 8px 0;
    }
  }

  .goods-count {
    margin-right: 0 !important;
  }
}

.total-price-wrap {
  color: #e34152;
  font-weight: 700;
  position: sticky;
  bottom: 0;
  background: #fff;
  width: 100%;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 0px 8px rgba(0, 0, 0, 0.05);
  z-index: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
